package com.ocom.webapi.controller;


import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ocom.common.constant.WebApiServiceUrl;
import com.ocom.common.entity.card.EntityXfMealInfo;
import com.ocom.common.request.exposeapi.LargeScreenRequest;
import com.ocom.common.request.payconfig.ChartListActionRequest;
import com.ocom.common.request.payconfig.TotalTurnoverRequest;
import com.ocom.common.resp.Result;
import com.ocom.common.utils.*;
import com.ocom.common.vo.pay.ChartListVo;
import com.ocom.common.vo.pay.GetTurnoverReportsVo;
import com.ocom.common.vo.webapi.CharVO;
import com.ocom.security.authentication.YoCiUser;
import com.ocom.security.utils.SecurityUtils;
import com.ocom.webapi.feign.MjRecodeClientService;
import com.ocom.webapi.feign.PayConfigClientService;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
//@PreAuthorize("@pms.hasRole('ROLE_WEB')")
public class ChartListController {


  @Autowired
  private PayConfigClientService payConfigClientService;

  @Autowired
  private MjRecodeClientService mjRecodeClientService;


  @PostMapping(WebApiServiceUrl.Url_ChartListAction)
  public Result chartListAction(@RequestBody ChartListActionRequest chartListAction) {
    YoCiUser yociuser = SecurityUtils.getYoCiUser();
    if (chartListAction.getAction().equals("turnover")) {
      TotalTurnoverRequest request = new TotalTurnoverRequest();
      request.setCompanyID(yociuser.getComId());
      request.setMerchID(-1l);
      request.setReportType(0);
      if (StringUtils.isNotEmpty(chartListAction.getSummaryDate())) {
        request.setSummaryDate(chartListAction.getSummaryDate());
      }
      request.setSummaryDate(DateUtils.getStrDate(new Date(), DateUtils.YYYY_MM));
      return ResultUtil.success(chartListTurnover(request).getData());
    }
    if (chartListAction.getAction().equals("recentlyAcTime")) {
      LargeScreenRequest request = new LargeScreenRequest();
      JSONObject param=new JSONObject();
      request.setCompanyId(String.valueOf(yociuser.getComId()));
      param.put("day", DateUtil.getDate());
      param.put("days",7);
      param.put("type",1);
      param.put("deptId",null);
      param.put("areaId",null);
      request.setParam(param);
      return ResultUtil.success(this.chartListRecentlyAcTime(request).getData());
    }

    return ResultUtil.success();
  }


  /**
   * 重新写
   * @param request
   * @return
   */
//  @PostMapping(WebApiServiceUrl.Url_ChartListTurnover)
  @Deprecated
  public Result chartListTurnoverQ(@RequestBody TotalTurnoverRequest request) {

    Result turnoverReports = payConfigClientService.getTurnoverReports(request);
    Map<String, Object> map = JSONObject.parseObject(
        JSONObject.toJSONString(turnoverReports.getData()),
        Map.class);

    if (ObjectUtil.isEmpty(map.get("dateList"))) {
      return ResultUtil.success(map);
    }
    List<Map<String, Object>> mapList = (List<Map<String, Object>>) map.get("dateList");

    // 获取餐段
    Result result = payConfigClientService.GetMealNameInfo(request.getCompanyID());
    Map<String, Object> mapMeal = JSONObject.parseObject(
        JSONObject.toJSONString(result.getData()),
        Map.class);
    List<EntityXfMealInfo> mealInfos = JSONObject.parseArray(
        JSON.toJSONString(mapMeal.get("list")), EntityXfMealInfo.class);
    List<String> mealNames = mealInfos.stream().map(EntityXfMealInfo::getMealName)
        .collect(Collectors.toList());
    List<CharVO> listMap2 = new ArrayList<>();

    Map<String, Object> xDateMap = new HashMap<>();
    List<String> xDate = new ArrayList<>();

    CharVO refundNumVo =new CharVO();
    refundNumVo.setName("退款订单数");
    CharVO amountVo =new CharVO();
    amountVo.setName("消费总金额");
    CharVO orderNumVo =new CharVO();
    orderNumVo.setName("消费订单数");

//    for (String mealName : mealNames) {
    // 按餐段组装订购数据
//    for (int i = 0; i < mealNames.size(); i++) {
      List<Integer> yDate = new ArrayList<>();
      //for (Map<String, Object> map1 : mapList) {
      // 每一天订购的餐
      for (int j = 0; j < mapList.size(); j++) {
        Map<String, Object> map1 = mapList.get(j);
//        yDate.add(0);
//        String date = (String) map1.get("strDate");
//        // 获取日期
//        Integer substring = Integer.valueOf(date.substring(8, 10));
        List<Map<String, Object>> mapList2 = (List<Map<String, Object>>) map1.get("detailList");

        // 获取一天餐段金额
        for (int x = 0; x < mapList2.size(); x++) {
          Map<String, Object> map2 = mapList2.get(x);
          xDate.add((String) map2.get("detail"));
          refundNumVo.getYData().add(map2.get("refundNum"));
          amountVo.getYData().add(map2.get("amount"));
          orderNumVo.getYData().add(map2.get("orderNum"));
        }
      }
//      mealNames.remove(i);
//      i = i - 1; // 注意 : 是删除元素后，要修正下下标的值,导致某元素被跳过
//    }
    xDateMap.put("xData",xDate);
    Map<String, Object> map1 = new HashMap<>();
    map1.put("xAxis",xDateMap);
    listMap2.add(refundNumVo);
    listMap2.add(amountVo);
    listMap2.add(orderNumVo);
    map1.put("series",listMap2);
    return ResultUtil.success(map1);
  }

  @PostMapping(WebApiServiceUrl.Url_ChartListTurnover)
  public Result chartListTurnover(@RequestBody TotalTurnoverRequest request) {
    Result turnoverReports = payConfigClientService.getTurnoverReports(request);
    GetTurnoverReportsVo getTurnoverReportsVo = JSON.parseObject(JSONObject.toJSONString(turnoverReports.getData()),GetTurnoverReportsVo.class);
    ChartListVo chartListVo = new ChartListVo();
    ChartListVo.XAxis axis = new ChartListVo.XAxis();
    Set<String> seriesName = new HashSet<>();
    Map<Integer,Map<String, ChartListVo.SeriesMap>> seriesMap = new HashMap<>();
    if(ObjectUtil.isNotEmpty(getTurnoverReportsVo.getDateList())){
      for (GetTurnoverReportsVo.DateData dateData:getTurnoverReportsVo.getDateList()) {
        Date rDate = cn.hutool.core.date.DateUtil.parse(dateData.getStrDate(), dateData.getDate());
        int date = cn.hutool.core.date.DateUtil.dayOfMonth(rDate);
        if(ObjectUtil.isEmpty(seriesMap.get(date))){
          seriesMap.put(date,new HashMap<>());
        }
        for (GetTurnoverReportsVo.DateData.Detail detail:dateData.getDetailList()){
          ChartListVo.SeriesMap seriesMapA = new ChartListVo.SeriesMap();
          seriesMapA.setAmount(detail.getAmount().divide(new BigDecimal(100),2,RoundingMode.HALF_UP).stripTrailingZeros());
          seriesMapA.setName(detail.getDetail());
          seriesMap.get(date).put(detail.getDetail(),seriesMapA);
          seriesName.add(detail.getDetail());
        }
      }
    }

    Date SummaryDate = cn.hutool.core.date.DateUtil.parse(getTurnoverReportsVo.getSummaryDate(),"yyyy-MM");
    Date dateStartTime = cn.hutool.core.date.DateUtil.beginOfMonth(SummaryDate);
    Date dateEndTime = cn.hutool.core.date.DateUtil.endOfMonth(SummaryDate);
    Date today = new Date();
    if(dateEndTime.after(today)){
      dateEndTime = today;
    }

    List<Integer> xAxisData = new LinkedList<>();
    Map<String,List<ChartListVo.SeriesMap>> finalSeriesMap = new HashMap<>();
    for (int i = cn.hutool.core.date.DateUtil.dayOfMonth(dateStartTime);i<=cn.hutool.core.date.DateUtil.dayOfMonth(dateEndTime);i++){
      int finalI = i;
      xAxisData.add(i);
      seriesName.forEach(name->{
          if(ObjectUtil.isEmpty(finalSeriesMap.get(name))){
            finalSeriesMap.put(name,new LinkedList<>());
          }
          ChartListVo.SeriesMap seriesMapA;
          if(ObjectUtil.isNotEmpty(seriesMap.get(finalI)) && ObjectUtil.isNotEmpty(seriesMap.get(finalI).get(name))){
            seriesMapA = seriesMap.get(finalI).get(name);
          }else{
            seriesMapA = new ChartListVo.SeriesMap();
            seriesMapA.setName(name);
            seriesMapA.setAmount(BigDecimal.ZERO);
//            seriesMapA.setAmount(new BigDecimal(RandomUtil.generateNumber(1)));
          }
          finalSeriesMap.get(name).add(seriesMapA);
      });
    }

    List<ChartListVo.Series> seriesList = new LinkedList<>();
    for (Map.Entry<String, List<ChartListVo.SeriesMap>> mapEntry: finalSeriesMap.entrySet()){
      ChartListVo.Series series = new ChartListVo.Series();
      series.setName(mapEntry.getKey());
      series.setData(mapEntry.getValue().stream().map(ChartListVo.SeriesMap::getAmount).collect(Collectors.toList()));
      seriesList.add(series);
    }
    axis.setData(xAxisData);
    chartListVo.setXAxis(axis);
    chartListVo.setXDate(seriesName);
    chartListVo.setSeries(seriesList);

    return ResultUtil.success(chartListVo);
  }
  @PostMapping(WebApiServiceUrl.Url_ChartListRecentlyAcTime)
  public Result chartListRecentlyAcTime(@RequestBody LargeScreenRequest request) {
    Map<String, Object> series = new HashMap<>();
    Map<String, Object> datas = new HashMap<>();
    List<Integer> yDate = new ArrayList<>();
    List<Integer> xDate = new ArrayList<>();
    Result result = mjRecodeClientService.recentlyAcTime(request);
    List<Map<String, Object>> mapList = (List<Map<String, Object>>) result.getData();
    for (Map<String, Object> map : mapList){
      String date = map.get("date").toString();
      Integer substring = Integer.valueOf(date.substring(8, 10));
      Integer openNum = (Integer) map.get("openNum");
      xDate.add(substring);
      yDate.add(openNum);
      series.put("xData",xDate);
      datas.put("name","出入门禁");
      datas.put("yData",yDate);
    }
    Map<String, Object> dataMap = new HashMap<>();
    dataMap.put("xAxis",series);
    List<Map> mapList1 =new ArrayList<>();
    mapList1.add(datas);
    dataMap.put("series",mapList1);
    System.out.println(dataMap);
    return ResultUtil.success(dataMap);
  }

}
